package com.springboot.utils;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.springboot.entity.Users;
import com.springboot.exception.CustomException;
import com.springboot.service.IUsersService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class JwtTokenUtils {
    private static IUsersService staticUsersService;
    private static final Logger log=LoggerFactory.getLogger(JwtTokenUtils.class);

    @Resource
    private IUsersService usersService;

    @PostConstruct
    public void setUserService(){
        staticUsersService=usersService;
    }
//    生成Token
    public static String getToken(String userId,String sign){
        return JWT.create().withAudience(userId).//将 id保存至Token作为载荷
                withExpiresAt(DateUtil.offsetHour(new Date(),2))//2小时后token过期
                .sign(Algorithm.HMAC256(sign));//以password作为token的密钥
    }
    //获取当前登录的用户信息
    public static Users getCurrentUser(){
        String token=null;
        try{
            HttpServletRequest request= (HttpServletRequest) ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            //1.获取token
            String authHeader = request.getHeader("Authorization");
            if (authHeader == null || authHeader.trim().isEmpty()) {
                throw new CustomException("请先登录（请求头缺少 Authorization 令牌）");
            }
            if (!authHeader.startsWith("Bearer ")) {
                throw new CustomException("令牌格式错误！正确格式为：Authorization: Bearer <your_token>");
            }
            token = authHeader.substring(7).trim();
            if (StrUtil.isBlank(token)){
                token=request.getParameter("token");
            }
            if (StrUtil.isBlank(token)){
                log.error("获取登录token失败，token：{}",token);
                return null;
            }
            //解析token
            String adminId= JWT.decode(token).getAudience().get(0);
            return staticUsersService.getById(Integer.valueOf(adminId));
        }catch (Exception e){
            log.error("获取信息失败，token：{}",token,e);
            return null;
        }
    }
}
